<script setup>
import { ref, onMounted, computed } from 'vue'
import {
  getFeedbackAPI,
  updateFeedbackAPI,
  deleteFeedbackAPI
} from '@/api/feedback'

// 搜索和分页相关
const searchForm = ref({
  status: '' // 状态筛选：空表示全部，1表示已解决，0表示未解决
})
const currentPage = ref(1)
const pageSize = ref(13) // 固定每页13条数据
const total = ref(0)
const feedbackData = ref([])
const loading = ref(false)

// 详情对话框
const dialogVisible = ref(false)
const currentFeedback = ref(null)

// 格式化状态文本
const formatStatusText = computed(() => (status) => {
  return status === 1 ? '已解决' : '未解决'
})

// 获取反馈列表
const getFeedbackList = async () => {
  if (loading.value) return

  try {
    loading.value = true

    const res = await getFeedbackAPI(
      searchForm.value.status || undefined,
      currentPage.value,
      pageSize.value
    )

    // 检查接口返回格式
    if (res.data.code === 1 && res.data.data) {
      const responseData = res.data.data
      feedbackData.value = responseData.records || []
      total.value = responseData.total || 0
    } else {
      ElMessage.warning('获取数据格式不正确')
      feedbackData.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('获取反馈列表失败')
    console.error('获取反馈列表错误:', error)
  } finally {
    loading.value = false
  }
}

// 查看详情
const handleView = (row) => {
  currentFeedback.value = { ...row }
  dialogVisible.value = true
}

// 修改反馈状态
const handleStatusChange = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = formatStatusText.value(newStatus)

  try {
    await ElMessageBox.confirm(
      `确定要将该反馈标记为${statusText}吗？`,
      '状态修改确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await updateFeedbackAPI(row.id, newStatus)
    row.status = newStatus
    ElMessage.success(`已成功标记为${statusText}`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('状态修改失败')
      console.error('状态修改错误:', error)
    }
  }
}

// 删除反馈
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除ID为${row.id}的反馈吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'danger'
      }
    )

    await deleteFeedbackAPI(row.id)
    ElMessage.success('删除成功')
    // 重新获取列表
    getFeedbackList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除错误:', error)
    }
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getFeedbackList()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    status: ''
  }
  currentPage.value = 1
  getFeedbackList()
}

// 分页改变
const handleCurrentChange = (val) => {
  // 限制最大页码为10
  if (val > 10) {
    currentPage.value = 10
    return
  }
  currentPage.value = val
  getFeedbackList()
}

// 页面挂载时加载数据
onMounted(() => {
  getFeedbackList()
})
</script>

<template>
  <div class="feedback-management">
    <div class="page-header">
      <h1>用户反馈</h1>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="全部状态"
            clearable
            style="width: 160px"
          >
            <el-option label="未解决" value="0" />
            <el-option label="已解决" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="feedbackData"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
      empty-text="暂无反馈数据"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="用户ID" width="100">
        <template #default="scope">{{ scope.row.userId }}</template>
      </el-table-column>
      <el-table-column
        prop="feedbackContent"
        label="反馈内容"
        min-width="300"
      />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ formatStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="提交时间" min-width="160" />
      <el-table-column label="操作" width="240">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleView(row)">
            查看
          </el-button>
          <el-button
            size="small"
            :type="row.status === 1 ? 'info' : 'success'"
            @click="handleStatusChange(row)"
          >
            {{ row.status === 1 ? '标记未解决' : '标记已解决' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        :max-pages="10"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 - 只显示反馈内容 -->
    <el-dialog v-model="dialogVisible" :title="'反馈详情'" :width="600">
      <div class="feedback-detail">
        <div class="content-container">
          <p class="content">{{ currentFeedback?.feedbackContent }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.feedback-management {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h1 {
      font-size: 1.5rem;
      color: #1a202c;
      margin: 0;
    }
  }

  .search-bar {
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .feedback-detail {
    .content-container {
      border: 1px solid #e5e7eb;
      border-radius: 6px;
      overflow: hidden;
    }

    .content {
      padding: 16px;
      line-height: 1.8;
      white-space: pre-wrap;
      word-break: break-all;
      margin: 0;
      min-height: 120px;
    }
  }
}
</style>
